﻿using Microsoft.Extensions.Options;
using ModelDto;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlserverManager
{
    public class DbConnectionFactory : IDbConnectionFactory
    {
        private string writeConn = "";
        private List<string> readConnectionList = new List<string>();
        //private SqlSugarClient? context =null;
        private readonly IOptions<SystemAppSettings> SysConfig;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="options"></param>
        public DbConnectionFactory(IOptions<SystemAppSettings> options)
        {
            SysConfig = options;

            //初始化连接字符串
            this.writeConn = SysConfig.Value.ConnectStrWrite;
            var connectStrs = SysConfig.Value.ConnectStrReads.Split('※');
            foreach (var item in connectStrs)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    this.readConnectionList.Add(item);
                }
            }
        }
        /// <summary>
        /// 获取上下文操作对象 SqlSugarClient
        /// </summary>
        /// <param name="dBWriteOrRead"></param>
        /// <returns></returns>
        public SqlSugarClient CreateDbContext()
        {
            List<SlaveConnectionConfig> list = new List<SlaveConnectionConfig>();

            foreach (var item in this.readConnectionList)
            {
                list.Add(new SlaveConnectionConfig() {
                    HitRate = 10,
                    ConnectionString=item.ToString()
                });
            }


            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = writeConn,
                DbType = DbType.SqlServer,
                //DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                SlaveConnectionConfigs = list

            }, db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) => //执行前
                {
                    //可更改SQL
                };
                db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
                {
                    //输出sql,查看执行sql 性能无影响
                    //Console.WriteLine(sql);
                    //获取原生SQL推荐 5.1.4.63  性能OK
                    //Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                    //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));


                    string sqlresult = sql;
                    var time = db.Ado.SqlExecutionTime.TotalMilliseconds;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "-->");
                    Console.ResetColor();
                    Console.WriteLine($"SQL语句:{sqlresult})执行时间:{time}ms");
                    Debug.WriteLine($"SQL语句:{sqlresult})执行时间:{time}ms");
                };

                db.Aop.OnError = (exp) =>//执行SQL 错误事件
                {
                    //exp.sql exp.parameters 可以拿到参数和错误Sql             
                };
            });

        }
    }
}
